# encoding=utf-8
import time
import threading
import datetime


class Util:

    _week_day = ("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日")

    @classmethod
    def get_time(cls, week=False):
        if week:
            return "%s  %s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
                               cls._week_day[datetime.datetime.now().weekday()])
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

    @classmethod
    def get_month_date(cls):
        date_list = []
        now = datetime.datetime.now()
        delta = datetime.timedelta(days=1)
        end_date = (now + datetime.timedelta(days=31)).strftime('%Y-%m-%d')
        while now.strftime('%Y-%m-%d') != end_date:
            date_list.append(now.strftime('%Y-%m-%d'))
            now += delta
        return date_list

    @classmethod
    def get_month_days(cls):
        return ['%s号' % i for i in range(1, 32)]

    @classmethod
    def get_week_day(cls):
        return cls._week_day

    @classmethod
    def sort_time(cls, time_list):
        time_dict = {}
        for ts in time_list:
            time_st = datetime.datetime.strptime(ts, '%H:%M')
            time_dict[ts] = time_st.hour * 60 + time_st.minute
        return list(dict(sorted(time_dict.items(), key=lambda x: x[1])).keys())

    @classmethod
    def human_time(cls, minute):
        if minute == 1:
            return '小于1分钟'
        elif minute < 60:
            return '%s分钟' % minute
        elif 60 <= minute < 1440:
            return '%s小时%s分钟' % (int(minute / 60), minute % 60)
        else:
            return '%s天%s小时%s分钟' % (int(minute / 1440), int((minute % 1440) / 60), int((minute % 1440) % 60))

    @classmethod
    def human_time_to_date(cls, to_date):
        return cls.human_time(int((to_date - datetime.datetime.now()).total_seconds() / 60) + 1)

    @classmethod
    def date_is_today(cls, date):
        if not date:
            return False
        return date.strftime("%Y-%m-%d") == datetime.date.today().strftime("%Y-%m-%d")

    @classmethod
    def get_today(cls):
        return datetime.date.today().strftime("%Y-%m-%d")

    @classmethod
    def format_time(cls, tt):
        tt_list = tt.split(':')
        if len(tt_list) != 2:
            return None
        h, m = tt_list
        if len(h) < 1 or len(h) > 2 or len(m) != 2:
            return None
        if h.startswith('0') and h != '0':
            h = h[1]
        if m.startswith('0'):
            m = m[1]
        if not (h.isdigit() and m.isdigit()):
            return None
        if int(h) > 23 or int(m) > 59:
            return None
        if len(tt_list[0]) == 1:
            return '0%s' % tt
        return tt

    @classmethod
    def create_thread(cls, func, args=()):
        th = threading.Thread(target=func, args=args)
        th.daemon = True
        th.start()
        return th


